#include "apue.h"

static void sig_quit(int);

int main(void) {
    sigset_t newmask, oldmask, pendmask;

    if (signal(SIGQUIT, sig_quit) == SIG_ERR)
        err_ret("cant caught sign SIGQUIT");

    /* Block SIGQUIT and save current signal mask */
    sigemptyset(&newmask);
    sigaddset(&newmask, SIGQUIT);
    if ((sigprocmask(SIG_BLOCK, &newmask, &oldmask)) < 0)
        err_ret("sigprocmask(SIG_BLOCK) error");

    sleep(5);       /* SIGQUIT here will remain pending */

    if ((sigpending(&pendmask)) < 0)
        err_sys("sigpending error");
    if (sigismember(&pendmask, SIGQUIT) > 0)
        printf("\nSIGQUIT pending\n");

    // restore oldmask which unblocks SIGQUIT
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
        err_sys("sigprocmask(SIG_SETMASK) error");
    printf("SIGQUIT unblocked\n");

    sleep(5);   /* SIGQUIT here will terminate with core file */

    return 0;
}

static void sig_quit(int) {
    if (signal(SIGQUIT, SIG_DFL) == SIG_ERR)
        err_sys("cant reset SIGQUIT");
    printf("caught SIGQUIT\n");
}
